import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  PlusOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { Button, Form, Image, Input, Modal, Select, Table, Upload, message } from 'antd';
import { useEffect, useState } from 'react';
import formatDate from '../../../util/formatDate';
import getFileNameFromPath from '../../../util/getFileNameFromPath';
import { allTenantList } from '@/services/ant-design-pro/tenantSet'

const Template = () => {
  //显示隐藏
  const [previewVisible, setPreviewVisible] = useState(false);
  const [visible, setVisible] = useState(false);
  const [downloadVisible, setDownloadVisible] = useState(false);

  //图片缩放url
  const [imageUrl, setImageUrl] = useState('');
  const [downloadId, setDownloadId] = useState('');
  const [downloadName, setDownloadName] = useState('');
  //
  const [templateDatas, setTemplateDatas] = useState([]);
  const [fileList, setFileList] = useState([]); //图片文件
  const [datFileList, setDatFileList] = useState([]);
  const [isEdit, setIsEidt] = useState(false);
  const [tenantOptions, setTenantOptions] = useState([]);
  const [form] = Form.useForm();
  const [downloadForm] = Form.useForm();

  useEffect(() => {
    fetchDataList();
    getTenantOptions();
  }, []);

  /**
   * 加载数据
   */
  const fetchDataList = () => {
    fetch(API_URL + '/template', {
      method: 'GET',
    })
      .then((res) => res.json())
      .then((data) => {
        setTemplateDatas(data);
      })
      .catch((error) => {
        message.error('获取数据失败：' + error);
      });
  };

  //获取租户选项数组
  const getTenantOptions = async () => {
    await allTenantList()
      .then((result) => {  
        //后端传过来的数组
        if (result.success) {
          if (result.data) {
            let options = [];
            result.data.forEach((e) => {
              let { tenantId, tenantName } = e;
              let option = {
                value: tenantId,
                label: tenantName,
              };
              options.push(option);
            });
            setTenantOptions(options);
          }
        }
      });
  };

  /**
   * 点击新增按钮
   */
  const hadleAdd = () => {
    setIsEidt(false);
    form.resetFields();
    setFileList([]);
    setDatFileList([]);
    setVisible(true);
  };
  /**
   * 点击修改按钮
   */
  const handleEdit = (record) => {
    setFileList([]);
    setDatFileList([]);
    form.setFieldsValue(record);
    setIsEidt(true);
    setVisible(true);
  };

  /**
   * 上传按钮
   */
  const handleUpload = async () => {
    try {
      const values = await form.validateFields();
      const formData = new FormData();
      formData.append('imgFile', values.image.file);
      formData.append('datFile', values.dat.file);
      formData.append('name', values.name);
      if (values.id) {
        formData.append('id', values.id);
      }
      fetch(API_URL + '/template', {
        method: values.id ? 'PUT' : 'POST',
        body: formData,
      })
        .then((e) => e.json)
        .then((data) => {
          message.success('上传成功');
          fetchDataList();
          setVisible(false);
        })
        .catch((e) => {
          throw new Error(e);
        });
    } catch (error) {
      message.error('上传失败：' + error);
    }
  };

  /**
   * 删除按钮
   * @param {*} id
   */
  const handleDelete = async (id) => {
    try {
      fetch(API_URL + `/template/${id}`, { method: 'DELETE' })
        .then((e) => e.json)
        .then((data) => {
          message.success('删除成功！');
          fetchDataList();
        })
        .catch((e) => {
          throw new Error(e);
        });
    } catch (error) {
      console.error('删除失败！错误：', error);
      message.error(error.message || '删除失败！');
    }
  };

  /**
   * 下载按钮
   */
  const handelDownload = async () => {
    const values = await downloadForm.validateFields();
    const formData = new FormData();
    formData.append('templateId', downloadId);
    formData.append('tenantId', values.tenantId);
    fetch(API_URL + '/template/download', {
      method: 'POST',
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('请求失败');
        }
        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = downloadName + '.dat'; // 下载文件的名称
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        setDownloadVisible(false);
        message.info('文件下载成功！');
      })
      .catch((error) => message.error('文件下载失败:', error));
  };
  const handleDownloadCancel = () => setDownloadVisible(false);

  /**
   * 表格列
   */
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'dat文件',
      dataIndex: 'datFileName',
      key: 'datFileName',
      render: (dat) => getFileNameFromPath(dat),
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      render: (time) => formatDate(time),
    },
    {
      title: '图片',
      dataIndex: 'imageURL',
      key: 'imageURL',
      render: (url) => (
        <div style={{ textAlign: 'center' }}>
          <Image src={API_URL + '/file/' + getFileNameFromPath(url)} width={200} />
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button
            type="link"
            icon={<DownloadOutlined />}
            onClick={() => {
              setDownloadVisible(true);
              setDownloadId(record.id);
              setDownloadName(record.name);
            }}
          >
            下载
          </Button>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            修改
          </Button>
          <Button type="link" icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </span>
      ),
    },
  ];

  /**
   * 表格数据
   */
  const data = templateDatas.map((e, index) => ({
    key: e.id,
    ...e,
  }));

  return (
    <div>
      <Button type="primary" onClick={hadleAdd} style={{ marginBottom: '20px' }}>
        <PlusOutlined /> 新增
      </Button>
      <Modal
        title={isEdit ? '修改' : '新增'}
        open={visible}
        onCancel={() => setVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setVisible(false)}>
            取消
          </Button>,
          <Button key="upload" type="primary" onClick={handleUpload}>
            上传
          </Button>,
        ]}
      >
        <Form form={form}>
          <Form.Item name="id" label="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="样板名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请填写样板名称!',
              },
            ]}
          >
            <Input disabled={isEdit} />
          </Form.Item>
          <Form.Item
            label="上传图片"
            name="image"
            rules={[
              {
                required: true,
                message: '请上传图片!',
              },
            ]}
          >
            <Upload
              fileList={fileList}
              beforeUpload={(file) => {
                const fileSizeLimit = 1024 * 1024 * 20; // 10MB
                if (file.size > fileSizeLimit) {
                  message.error('文件大小不能超过20MB!');
                } else {
                  setFileList([file]);
                }
                return false;
              }}
            >
              <Button icon={<UploadOutlined />}>选择图片</Button>
            </Upload>
          </Form.Item>
          <Form.Item
            label="上传dat文件"
            name="dat"
            rules={[
              {
                required: true,
                message: '请上传.dat文件!',
              },
            ]}
          >
            <Upload
              fileList={datFileList}
              beforeUpload={(file) => {
                setDatFileList([file]);
                return false;
              }}
              accept=".dat"
            >
              <Button icon={<UploadOutlined />}>选择dat文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Table
        dataSource={data}
        columns={columns}
        bordered={true}
        pagination={false}
        style={{ marginTop: '20px' }}
      />

      <Modal
        open={downloadVisible}
        onCancel={handleDownloadCancel}
        footer={[
          <Button key="cancel" onClick={() => setDownloadVisible(false)}>
            取消
          </Button>,
          <Button key="upload" type="primary" onClick={handelDownload}>
            下载
          </Button>,
        ]}
      >
        <Form form={downloadForm}>
          <Form.Item
            label="租户名称"
            name="tenantId"
            rules={[
              {
                required: true,
                message: '请选择租户!',
              },
            ]}
          >
            <Select options={tenantOptions} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Template;
